package com.example.producer.listeners;

import com.alibaba.fastjson.JSON;
import com.example.producer.pojo.Order;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Component
/*
    txProducerGroup="orderTx" 用来区分不同业务处理的事务消息回调
        比如 orderTx 用来处理订单支付的
            LogisticsTx 用来处理物流相关事务
 */
@RocketMQTransactionListener(txProducerGroup="orderTx")
public class OrderTransMsgListener implements RocketMQLocalTransactionListener {

    /*
        执行本地事务的回调方法
            当rocketmq半消息主题收到消息后，会触发这个回调
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        //这个方法在rocketmq内部返回的数据是固定的，是byte[]
        byte[] payload = (byte[]) msg.getPayload();
        String orderStr = new String(payload, StandardCharsets.UTF_8);

        Order order = JSON.parseObject(orderStr, Order.class);

        //执行支付业务
        if (order.getId() == 1){
            //支付失败
            System.out.println("支付失败...");
            return RocketMQLocalTransactionState.ROLLBACK;
        }else if (order.getId() == 2){
            //支付成功
            System.out.println("支付成功...");
            return RocketMQLocalTransactionState.COMMIT;
        }

        //状态未知
        return RocketMQLocalTransactionState.UNKNOWN;
    }

    /*
        执行本地事务回查的方法
            当rocketmq半消息主题收到的状态时UNKNOW状态时，会触发这个回调
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        //回查本地订单事务的结果，根据查询的结果，返回对应的状态

        System.out.println("状态回查：" + LocalDateTime.now());

        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
